// src/main/java/tech/aistar/controller/UserController.java
package tech.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import tech.aistar.pojo.User;
import tech.aistar.service.UserService;
import tech.aistar.utils.JwtUtils; // 添加JWT工具类导入
import tech.aistar.pojo.ResultReturn; // 添加ResultReturn导入

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制层
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * localhost:8088/dev/user/849962874@qq.com
     * @param email
     * @return
     */
    @GetMapping("{email}")
    public ResultReturn<String> sendCode(@PathVariable("email") String email){
        //1. 先判断用户是否存在
        User user = userService.getByEmail(email);
        if(user == null)
            return ResultReturn.fail("sorry,email is not exist!");
        //2. 说明email是存在的,则发送验证码
        userService.sendCode(email);
        return ResultReturn.success("验证码已经发送!请查看邮箱!");
    }

    /**
     * 登录的业务逻辑
     * @param email
     * @param code
     * @return
     */
    @PostMapping("{email}/{code}")
    public ResultReturn register(@PathVariable("email") String email,@PathVariable("code") String code){
        //1. 先判断用户是否存在
        User user = userService.getByEmail(email);
        if(user == null)
            return ResultReturn.fail("sorry,email is not exist!");
        //2. 说明email是存在的,校验验证码
        //根据key到redis中获取验证码
        String serverCode = (String) redisTemplate.opsForValue().get(email);
        //3. 判断验证码是否正确
        if(serverCode == null){
            return ResultReturn.fail("验证码已过期!");
        }
        //4. 验证码是存在的,则登录成功
        if(serverCode.equals(code)){
            //TODO... 登录成功
            //1. 生成token
            String token = JwtUtils.generateToken(user);
            //2. 响应token给客户端
            //TODO 9.24 success
            //TODO.. server除了返回token给客户端,还需要将登录的用户的username一并返回给客户端
            //需要定义一个Map集合来封装token和username
            Map<String,String> map = new HashMap<>();
            map.put("token",token);
            map.put("username",user.getUsername());
            return ResultReturn.success(map);
        }
        //5. 未知情况
        return ResultReturn.fail("验证码错误,请重新登录!");
    }
}
